import http from '@ohos.net.http';
import util from '@ohos.util';

export interface ApiResponse<T> {
  code: number;
  message: string;
  data: T;
}

class HttpRequestUtil {
  httpRequest: http.HttpRequest = http.createHttp()

  async get<T>(url: string, parms: string): Promise<T> {
    let httpOptions: http.HttpRequestOptions = {
      extraData: parms,
      expectDataType: http.HttpDataType.STRING
    }

    // console.log('httpUtils.ts -> get -> request begin ')
    let res = await this.httpRequest.request(url, httpOptions)

    // console.log('httpUtils.ts -> get -> res.result: ', res.result)

    let responseText = ''
    if (res.result instanceof String) {
      responseText = res.result as string
    } else if (res.result instanceof ArrayBuffer) {
      responseText = new util.TextDecoder().decodeToString(new Uint8Array(res.result))
    } else {
      responseText = res.result as string
    }
    // console.log('httpUtils.ts -> get -> responseText: ', responseText)
    const modelT = JSON.parse(responseText) as T
    // console.log('httpUtils.ts -> get -> modelT: ', modelT)

    // 返回反序列化后的 User 对象
    return modelT;
  }
}

export const httpUtils: HttpRequestUtil = new HttpRequestUtil()